package org.blog.service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.blog.config.UrlConfig;
import org.blog.helper.Constants;
import org.blog.model.BaseModel;
import org.blog.model.ModelPassport;
import org.springframework.beans.factory.annotation.Autowired;

public class ServiceLog {

	@Autowired
	private UrlConfig urlConfig;

	private void log(String str) {
		// TODO
	}

	public void log(HttpServletRequest request, BaseModel baseModel, int code) {

		String cookieValue = cookieValue(findCookie(request));
		String servletPath = request.getServletPath();
		ModelPassport passport = getSessionUser(request.getSession());
		String user = null;
		if (passport != null) {
			user = passport.getUsername();
		}

		Integer id = null;
		if (baseModel != null) {
			id = baseModel.getId();
		}

		String log = construts(cookieValue, servletPath, user, id, code);
		if (log != null) {
			log(log);
		}

	}

	/** 组装日志字符串 */
	private String construts(String cookieValue, String servletPath,
			String user, Integer id, Integer code) {
		// 对所有操作日志进行记录
		StringBuilder builder = new StringBuilder();
		builder.append("[sid:").append(cookieValue);
		builder.append(",user:").append(user);
		builder.append("] visit ")
				.append(urlConfig.getChinaServiceName(servletPath))
				.append(" at ").append(System.currentTimeMillis() / 1000)
				.append(". With the data id :");
		builder.append(id);
		builder.append(". and the result code is:").append(code);
		return builder.toString();
	}

	private ModelPassport getSessionUser(HttpSession session) {
		return (ModelPassport) session.getAttribute(Constants.SESSION_KEY);
	}

	private Cookie findCookie(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (Constants.COOKIE_NAME.equals(cookie.getName())) {
					return cookie;
				}
			}
		}
		return null;
	}

	private String cookieValue(Cookie cookie) {
		if (cookie != null) {
			return cookie.getValue();
		}
		return null;
	}
}
